<!-- 担保人管理 -->
<template>
	<div class="m-view-guarantorManager m-window">
		<!-- 搜索头 -->
		<div class="m-condition">
			<el-row :gutter="5">
				<el-form
					:model="formSearch"
					ref="formSearch"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="6">
						<el-form-item label="姓名" class="rightItem">
							<el-input
								value-key="id"
								v-model="formSearch.guarantorName"
								placeholder="请输入担保人名称"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-checkbox @change="search" v-model="formSearch.state">显示停用</el-checkbox>
					</el-col>
				</el-form>

				<el-col :span="2" :offset="8">
					<el-button type="primary" @click="search">查询</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="addGuarantor()">新增</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" v-show="formSearch.state" @click="changeState(0)">启用</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" v-show="!formSearch.state" @click="changeState(1)">停用</el-button>
				</el-col>
			</el-row>
		</div>

		<!-- 表格 -->
		<div class="m-agTable m-bottom" v-loading="loading">
			<agGridComponents
				ref="agGridComponent"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
				:getRowSelection="'single'"
				:isColFit="true"
			></agGridComponents>
		</div>

		<!-- 页脚 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200 ]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 完善担保人信息 -->
		<el-dialog
			title="担保人信息"
			:visible.sync="dialogVisible"
			v-dialogDrag
			:close-on-click-modal="false"
			:before-close="cancel"
			class="guarantorDialog"
			v-loading="loading"
		>
			<el-form label-width="100px" :rules="rules" ref="ruleForm" :model="ruleForm">
				<el-form-item label="姓名" prop="guarantorName">
					<el-input placeholder="请输入担保人姓名" v-model="ruleForm.guarantorName" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item label="身份证" prop="idCard">
					<el-input placeholder="请输入担保人身份证" v-model="ruleForm.idCard" auto-complete="off" maxlength="18"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input placeholder="请输入手机号" v-model="ruleForm.phone" maxlength="11"></el-input>
					<el-button @click="getVerifyCode" :disabled="isMayGet">{{verifyCodeBtnText}}</el-button>
				</el-form-item>
				<el-form-item label="验证码" prop="verifyCode">
					<el-input
						placeholder="请输入验证码"
						v-model="ruleForm.verifyCode"
						maxlength="6"
						auto-complete="off"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="电子签账号" prop="esignAccount">
					<el-input
						placeholder="请输入已注册电子签账号"
						type="mail"
						v-model="ruleForm.esignAccount"
						auto-complete="off"
						maxlength="50"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="电子签网址">
					<el-link :href="esignUrl" target="_blank" type="primary" :underline="false">{{esignUrl}}</el-link>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取消</el-button>
				<el-button type="primary" @click="save" :loading="saveing">保存</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import localeText from "@/i18n/agGridText";
import agGridComponents from "@/components/agGridComponents.js";
import Msg from "@/public/message";
import constant from "@/public/constant";

export default {
	components: {
		agGridComponents,
	},
	data () {
		let vaildPhone = (rule, value, callback) => {
			let reg = /^1(3[0-9]|4[0-9]|5[0,1,2,3,5,6,7,8,9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/;
			if (!reg.test(value)) {
				callback(new Error("请输入11位符合要求的手机号码"));
			} else {
				callback();
			}
		}
		let vaildIdCard = (rule, value, callback) => {
			let reg = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/g;
			if (!reg.test(value)) {
				callback(new Error("请输入正确格式的身份证号码!"));
			}
			else {
				callback();
			}
		}
		return {
			formSearch: {//查询表
				guarantorName: '',
				state: false,
			},
			dialogVisible: false,
			rowData: [], // 表格数据
			//表格参数
			gridOptions: '',
			columnDefs: [],
			//页脚参数
			pageInfo: {
				pageSize: 30,
				total: 0,
				current: 1,
			},
			loading: false,
			// 表单内容
			ruleForm: {
				guarantorName: "",
				phone: "",
				idCard: '',
				verifyCode: '',
				esignAccount: ''
			},
			// 验证规则
			rules: {
				guarantorName: [
					{ required: true, trigger: "blur", message: '请输入担保人姓名' },
					{ min: 1, max: 50, message: '最大输入50个字符！', trigger: 'blur' }
				],
				idCard: [
					{ required: true, trigger: "blur", validator: vaildIdCard }
				],
				verifyCode: [
					{ required: true, trigger: "blur", message: '请输入验证码' }
				],
				phone: [
					{ required: true, trigger: "blur", validator: vaildPhone }
				],
				esignAccount: [
					{ required: true, trigger: "blur", message: '请输入电子签账号' }
				]
			},
			// 定时器
			timer: null,
			verifyCodeBtnText: '获取验证码',
			// 获取验证码按钮状态 
			isMayGet: false,
			saveing: false,
			// 电子签网址
			esignUrl: ''
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		this.columnDefs = [
			{
				headerName: "姓名", field: "guarantorName", width: 120,
				checkboxSelection: true,
			},
			{ headerName: "电子签账号", field: "esignAccount", width: 120 },
			{ headerName: "手机号", field: "phone", width: 120 },
			{
				headerName: "状态", field: "state", width: 100,
				cellRenderer: (params) => {
					if (params.value == 0) {
						return '启用';
					} else {
						return '停用';
					}
				}
			},
		];

	},
	mounted () {
		this.search();
		this.esignUrl = constant.appenv == 'app' ? 'https://esign.lesso.com/esign' : 'https://esign.lesso.com/testesign'
	},
	methods: {
		//   获取验证码
		getVerifyCode () {
			let second = 60;
			if (this.timer) clearInterval(this.timer);
			this.isMayGet = true
			this.$http.getAuthCode({ phone: this.ruleForm.phone }).then(({ data }) => {
				if (data.code == 1) {
					this.timer = setInterval(() => {
						if (second > 1) {
							this.verifyCodeBtnText = `${--second}秒后失效`;
						} else {
							clearInterval(this.timer);
							this.verifyCodeBtnText = "重新获取";
							this.isMayGet = false;
						}
					}, 1000);
				} else {
					Msg.showErrorMsg(data.info)
					this.isMayGet = false
				}
			}).catch(err => {
				this.isMayGet = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		//查询 
		search () {
			this.loading = true;
			let params = {
				eqParams: {
					supplierCode: this.$global.supplierData.supplierCode,
					state: this.formSearch.state ? 1 : 0,
				},
				likeParams: {
					name: this.formSearch.guarantorName
				},
				size: this.pageInfo.pageSize,
				current: this.pageInfo.current,
			};
			this.$http.getGuarantorList(params).then(({ data }) => {
				this.loading = false;
				if (data.code == 1) {
					this.rowData = data.rows;
					this.pageInfo.total = data.total
					this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
				.catch(err => {
					this.loading = false;
					Msg.showErrorMsg(err.data.message)
				});
		},
		//停用&启用 0停用,1启用
		changeState (state) {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (row.length < 1) {
				this.$alert("提示：请选择需要停用的担保人", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			let params = {
				id: row[0].id,
				state: state,
				modifyer: this.$global.user.employeeName,
				modifyerId: this.$global.user.id
			}
			this.$confirm(`是否确认${this.formSearch.state ? '启用' : '停用'}该担保人`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				this.$http.unableGuarantor(params).then(({ data }) => {
					this.loading = false;
					if (data.code == 1) {
						this.$message({
							message: `${this.formSearch.state ? '启用' : '停用'}成功！`,
							type: "success"
						});
						this.search();//刷新
					} else {
						Msg.showErrorMsg(data.info)
					}
				})
					.catch(err => {
						this.loading = false;
						Msg.showErrorMsg(err.data.message)
					});
			})
		},
		// 新增担保人信息
		addGuarantor () {
			this.dialogVisible = true
		},
		//保存&保存并继续
		save () {
			this.$refs['ruleForm'].validate((valid) => {
				if (valid) {
					this.saveing = true
					const { phone, verifyCode } = this.ruleForm
					// this.saveGuarantorInfo()
					// return
					this.$http.validaAuthCode({ verifyNum: verifyCode, phone }).then(({ data }) => {
						if (data.code == 1) {
							this.saveGuarantorInfo()
						} else {
							this.saveing = false
							Msg.showErrorMsg(data.info)
						}
					}).catch(err => {
						this.saveing = false
						Msg.showErrorMsg(err.data.message)
					})
				}
			})
		},
		// 保存担保人信息
		saveGuarantorInfo () {
			const { guarantorName, phone, idCard, esignAccount } = this.ruleForm
			let params = {
				guarantorName,
				phone,
				idCard,
				esignAccount,
				esignState: 0,
				supplierAccount: this.$global.user.userName,
				supplierCode: this.$global.supplierData.supplierCode,
				creator: this.$global.user.employeeName,
				creatorId: this.$global.user.id
			}
			this.$http.saveGuarantorInfo(params).then(({ data }) => {
				this.saveing = false
				if (data.code == 1) {
					this.cancel()
					this.search()
				} else {
					this.saveing = false
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.saveing = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		//弹框取消按钮
		cancel () {
			this.dialogVisible = false;
			this.ruleForm = {
				guarantorName: "",
				phone: "",
				idCard: '',
				verifyCode: '',
				esignAccount: ''
			}
		},
		//一页显示的总条数发送变化时触发
		handleSizeChange (val) {
			this.pageInfo.pageSize = val;
			this.search();
		},

		//页数变化时
		handleCurrentChange (val) {
			this.pageInfo.current = val;
			this.search();
		},
	}
}
</script>
<style lang="less" scoped>
.m-view-guarantorManager {
	.guarantorDialog {
		/deep/.el-form {
			/deep/.el-form-item:nth-child(3) {
				.el-form-item__content {
					display: flex;
					.el-button {
						margin-left: 12px;
					}
				}
			}
		}
	}
}
</style>